<?php

namespace App\Dao;

use App\Constants\CodeData;
use App\Exception\MessageException;
use App\Model\CommonSetting;
use App\Model\Order;
use App\Utils\RedisClient;
use Hyperf\Context\ApplicationContext;

class CommonSettingDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }

    public function getList($key)
    {
        $redisKey = 'tb_common_setting:' . $key;
        $setting = RedisClient::getInstance()->get($redisKey);
        if ($setting) {
            return json_decode($setting, true);
        } else {
            $data = CommonSetting::query()->where('key', $key)->first();
            if (empty($data)) {
                return [];
            } else {
                RedisClient::getInstance()->set($redisKey, json_encode($data, JSON_UNESCAPED_UNICODE));
                return $data;
            }
        }

    }

    public static function getJsonValue($key)
    {
        $result = (new self())->getList($key);
        if (empty($result) || empty($result['value'])) {
            throw new MessageException('未配置该功能', CodeData::NO_PROMPT);
        }
        return json_decode($result['value'], true);
    }


    // 微信功能开启状态判断
    public static function getWxSwitch($userInfo)
    {
        $wx_show = 0;
        $wx_setting = self::getJsonValue("USER_WX_SETTING");
        $channels = $wx_setting['channels'];
        if (!empty($channels)) {
            $channels = array_column($channels, 'status', 'channel');
        } else {
            $channels = [];
        }

        if (($wx_setting['wx_switch'] == 1 && $userInfo['sex'] == 2 && !empty($userInfo['guild_num'])) || $wx_setting['wx_switch'] == 2) {
            $wx_show = 1;
        }

        if (isset($channels[$userInfo['channel']])) {
            $wx_show = $channels[$userInfo['channel']];
        }

        if ($userInfo['sex'] == 1) {
            $recharge = Order::query()->where('pay_status', 1)->where('uid', $userInfo['id'])->sum('price');
            if ($recharge > 5000) {
                $wx_show = 0;
            }
        }

        return $wx_show;
    }

    public static function getValue(string $key, $default = 0)
    {
        $result = (new self())->getList($key);
        if (empty($result) || empty($result['value'])) {
            return $default;
        }
        $value = json_decode($result['value'], true);
        return $value ?? $default;
    }

}